
package com.sihan.framework.etm.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author gsl
 * @version 1.0
 * 
 */
@Slf4j
public final class RegexpUtils {

	private RegexpUtils() {
	}
	/**
	 * 验证是否数字
	 */
	public final static String ALL_NUM = "^(\\-|\\+)?\\d+(\\.\\d+)?$";
	public final static String ALL_NUM_TIP = "全部为数字";
	public final static String NUM_OR_STR = "[0-9A-Za-z]*";
	public final static String PURE_IS_NUM = "^(\\-|\\+)?[0-9]{1,4}";
	public final static String PURE_IS_NUM_TIPS = "必须为不超过4位数字";
	public final static String TYPE_IS_ERR_TIPS = "类型错误";
	
	public final static String IS_NUM = "^(\\-|\\+)?\\d+(\\.\\d+)?$";
	/**
	 * 链接
	 */
	public final static String IS_URL = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)\\/\\/(([a-zA-Z\\.])+|([0-9\\.])+(:\\d{2,5})?)(\\/{1,2}|\\\\{1,2}|\\?)+([a-zA-Z0-9-_\\.\\?\\&=*~](\\/+|\\\\+)?)*";
	/**
	 * 邮箱
	 */
	public final static String IS_MAIL = "[a-zA-Z0-9_\\-\\.]+@(sina|qq|163)+(\\.(com|cn|org|edu|hk))";
	/**
	 * 不包含特殊字符
	 */
	public final static String NOT_SPECIAL ="^[^`~!@#$^&*()=|{}':;',\\[\\]<>/?~！@\\+#￥……&*（）——|{}【】’‘《》；：”“'。，、？\\\\]*$";
	/**
	 * 包含特殊字符
	 */
	public final static String IS_SPECIAL ="[`~!@#$^&*()=|{}':;',\\[\\]<>/?~！@\\+#￥……&*（）——|{}【】’‘《》；：”“'。，、？\\\\]";
	/**
	 * 资源链接
	 */
	public final static String IS_RES ="^[A-Za-z/]+$";
	/**
	 * 类型0或者1
	 */
	public final static String IS_TYPE ="(1|2|0)";
	/**
	 * 取出所有%号格式数据
	 */
	public final static String HAS_PER_CENT = "%[^%.]{1,2}";
	public final static String IS_ESCAPE  = "%[a-z0-9]{2}";
	/**
	 * 空格
	 */
	public static final String CLEAR_BLANK = "\\s*|\t|\r|\n";
	/**
	 * 验证常用后缀
	 */
	public static final String IS_SUFFIX = ".*(.jpg|.gif|.png|.bmp|.jpeg|.zip|.rar|.xls|.xlsx|.docx|.doc|.pdf|.ppt|.pptx)$";
	/**
	 * 完整匹配
	 * @param source 待验证字符串
	 * @param exp 规则
	 * @return
	 */
	public static boolean matched(String source, String exp) {
		Pattern p = Pattern.compile(exp);
		Matcher m = p.matcher(source);
		return m.matches();
	}
	/**
	 * 部分匹配
	 * @param source 待验证字符串
	 * @param exp 规则
	 * @return
	 */
	public static boolean find(String source, String exp) {
		Pattern p = Pattern.compile(exp);
		Matcher m = p.matcher(source);
		return m.matches();
	}
	/**
	 * 在字符串中提取数字
	 * @param apPreLevelCode
	 * @return double
	 */
	public static double digits(String apPreLevelCode) {
		Pattern p = Pattern.compile("(\\d+\\.\\d+)|(\\d+)");
		Matcher m = p.matcher(apPreLevelCode);
		m.find();
		String s = m.group();
		return Double.parseDouble(s);
	}
	/**
	 * 替换所有非转义%号
	 **/
	public static String formatPerCent(String str) {
		StringBuffer sb= new StringBuffer(str);
		Pattern p = Pattern.compile(
		HAS_PER_CENT, Pattern.MULTILINE | Pattern.DOTALL);
		Matcher m = p.matcher(str);
//		String newStr = str;
		AtomicInteger ai = new AtomicInteger(0);
		while(m.find()) {
			/*String g = addSprit(m.group());
			String rep = "";
			if(g.length()<=2 || !isEscape(g)) {
				rep = m.group().replaceAll("%", "%25");
			}
			if(!"".equals(rep)) {
				newStr = newStr.replaceAll(g, rep);
			}*/
			String g = m.group();
			int i = m.start()+ai.get()+1;
			if(g.length()<=2 || !isEscape(g)) {
				sb.insert(i, "25");
				ai.addAndGet(2);
			}
		}
		return sb.toString();
	}
//	/**
//	 * 所有特殊字符加/
//	 * @param group
//	 * @return
//	 */
//	private static String addSprit(String group) {
//		StringBuffer sb= new StringBuffer(group);
//		Pattern p  = Pattern.compile(IS_SPECIAL,Pattern.MULTILINE | Pattern.DOTALL);
//		Matcher m = p.matcher(group);
//		AtomicInteger ai = new AtomicInteger(0);
//		while(m.find()) {
//			int i = m.start()+ai.get();
//			sb.insert(i, "\\");
////			ai.addAndGet(2);
//			ai.incrementAndGet();
//		}
//		return sb.toString();
//	}
	/**
	 * 判断%后面两位是否只有字母或数字
	 * @param str
	 * @return
	 */
	public static boolean isEscape (String str) {
		Pattern p = Pattern.compile(
				IS_ESCAPE,Pattern.MULTILINE | Pattern.DOTALL);
				Matcher m = p.matcher(str);
		return m.matches();
		
	}
	/**
	 * 清除空格
	 * @param s
	 * @param clearBlank
	 * @return
	 */
	public static String clearBlank(String s) {
		String str="";
		try {
			str = URLDecoder.decode(formatPerCent(s),"utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error("异常",e);
		}
		if(str!=null && !"".equals(str)) { 
            Pattern p = Pattern.compile(CLEAR_BLANK);   
            Matcher m = p.matcher(str);   
            String strNoBlank = m.replaceAll("");   
            return strNoBlank;   
        }else {   
            return str;   
        }        
	}
	public static void main(String[] args) {
	/*	Pattern p = Pattern.compile("(%)",Pattern.UNICODE_CASE|Pattern.CANON_EQ|Pattern.CASE_INSENSITIVE|Pattern.COMMENTS|Pattern.DOTALL|Pattern.LITERAL|Pattern.MULTILINE|Pattern.UNICODE_CHARACTER_CLASS);
		Matcher m = p.matcher("%%25");
		System.out.println(m.matches());*/
		/*try {
			URLDecoder.decode("%bb", "utf8");
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}*/
	/*	Pattern p = Pattern.compile(IS_SPECIAL,Pattern.CASE_INSENSITIVE|Pattern.DOTALL|Pattern.MULTILINE);
		Matcher m = p.matcher("%dasfa￥%……");
		System.out.println(m.find());*/
//		System.out.println(RegexpUtils.clearBlank("SFA%20DF%$^%25"));
//		System.out.println(RegexpUtils.addSprit("DS##@FA%DF%$^&%25"));
//		System.out.println("%^2%25dadfasdf%8".replaceAll("%^2".replaceAll("\\^", "\\\\^"), "%25^2"));
	}
	
}
